import json

from django.http import HttpResponseRedirect

from home.models import Article, ArticleCategory


def common_data(request):
    # 1、获取所有分类信息数据
    categories = ArticleCategory.objects.all()
    # 2、接受用户点击的分类id
    cat_id = request.GET.get('cat_id', 1)
    # 3、根据分类id进行分类的查询
    try:
        category = ArticleCategory.objects.filter(id=cat_id).first()
    except ArticleCategory.DoesNotExist:
        return HttpResponseRedirect('此分类信息不存在')
    # 5、根据分类信息查询该分类下的所有文章数据
    articles = Article.objects.filter(category=category)
    news_art = Article.objects.order_by('-create_time')[0:2]
    hot_tags = Article.objects.values('tags').order_by('-total_views').distinct()[:9]

    if request.COOKIES.get('login_name') is not None:
        username = json.loads(request.COOKIES.get('login_name'))
    else:
        username = ""

    return {"newArt":news_art,
            "hotTags":hot_tags,
            'categories': categories,
            'category': category,
            'username':username
            }
